package com.greensam.pixelengine.manager.upload;

import cn.hutool.core.io.FileUtil;
import com.greensam.pixelengine.exception.ThrowUtils;
import com.greensam.pixelengine.pojo.emuns.ErrorCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;

/**
 * 文件图片上传
 *
 * @author Macro_Ray
 * @since 2025/7/19 15:52
 */
@Slf4j
@Service
public class FilePictureUpload extends PictureUploadTemplate {

    @Override
    protected void validPicture(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        ThrowUtils.throwIf(multipartFile.isEmpty(), ErrorCodeEnum.ParamValidError, "文件不能为空");
        // 1. 校验文件大小
        long fileSize = multipartFile.getSize();
        final long oneMb = 1024 * 1024L;
        ThrowUtils.throwIf(fileSize > 2 * oneMb, ErrorCodeEnum.ParamValidError, "文件大小不能超过2M");
        // 2. 校验文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        // 允许上传的文件后缀
        final List<String> allowSuffixList = List.of("jpg", "jpeg", "png", "gif", "webp");
        ThrowUtils.throwIf(!allowSuffixList.contains(fileSuffix), ErrorCodeEnum.ParamValidError, "文件格式不正确");
    }

    @Override
    protected String getOriginFilename(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        return multipartFile.getOriginalFilename();
    }

    @Override
    protected void processFile(Object inputSource, File file) throws Exception {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        multipartFile.transferTo(file);
    }
}
